package org.esisar.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import org.esisar.model.Album;
import org.esisar.model.Model;
import org.esisar.model.OrderLine;

public class OrderLineStatementCreator implements StatementCreator{


	private PreparedStatement preparedStatement;
	
	@Override
	public PreparedStatement addStatement(Connection connection, Model model) throws SQLException {
		
		OrderLine orderLine = modelToOrderLine(model);
			
		preparedStatement = connection.prepareStatement("INSERT INTO orderLine (quantity,price,idOrder,idAlbum,idSize) VALUES(?,?,?,?,?)");

		fillModel(orderLine);
	
		return preparedStatement;
		
	}

	@Override
	public PreparedStatement deleteStatement(Connection connection, List<Long> keys) throws SQLException {

		preparedStatement = connection.prepareStatement("DELETE FROM orderLine WHERE idOrder = ? AND idAlbum = ? AND idSize = ?");

		preparedStatement.setLong(1, keys.get(0));
		preparedStatement.setLong(2, keys.get(1));
		preparedStatement.setLong(3, keys.get(2));
				
		return preparedStatement;
	}

	@Override
	public PreparedStatement updateStatement(Connection connection, Model model)
			throws SQLException {
		
		OrderLine orderLine = modelToOrderLine(model);
		
		preparedStatement = connection.prepareStatement("UPDATE orderLine SET quantity = ?, price = ? WHERE idOrder = ? AND idAlbum = ? AND idSize = ?");

		fillModel(orderLine);
		
		return preparedStatement;
	}

	private void fillModel(OrderLine orderLine) throws SQLException {
		preparedStatement.setInt(1, orderLine.getQuantity());
		preparedStatement.setFloat(2, orderLine.getPrice());
		preparedStatement.setLong(3, orderLine.getIdOrder());
		preparedStatement.setLong(4, orderLine.getIdAlbum());
		preparedStatement.setLong(5, orderLine.getIdSize());		
	}

	private OrderLine modelToOrderLine(Model model) {
		OrderLine orderLine;
		
		if (model instanceof OrderLine){
			orderLine = (OrderLine) model;
		}else{
			throw new ClassCastException("Bad object instance");
		}
		return orderLine;
	}
	
	@Override
	public PreparedStatement readStatement(Connection connection, String field,
			String value) throws SQLException {
		preparedStatement = connection.prepareStatement("SELECT * FROM orderLine WHERE " + field + " LIKE ? ");

		preparedStatement.setString(1, value);
		
		return preparedStatement;
	}

	@Override
	public Model fillModel(ResultSet rs) throws SQLException {
		String idOrder = rs.getString("idOrder");
		String idAlbum = rs.getString("idAlbum");
		String idSize = rs.getString("idSize");
		int qty = rs.getInt("quantity");
		float price = rs.getFloat("price");
		
		OrderLine ol = new OrderLine(Long.parseLong(idOrder), Long.parseLong(idAlbum), Long.parseLong(idSize), qty, price);
		
		return ol;
	}

}